package com.hr.最大连续子序列和;

/**
 * @program: leetcode
 * @description:
 * @author: HuRan QQ1345122890
 * @create: 2021-05-30 14:23
 */
public class Main {
    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4 - 1, 2, 1, -5, 5};
        System.out.println(maxSubarray3(nums, 0, nums.length));
    }

    //暴力法
    private static int maxSubarray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = Integer.MIN_VALUE;
        for (int begin = 0; begin < nums.length; begin++) {
            for (int end = begin; end < nums.length; end++) {
                int sum = 0;
                for (int i = begin; i <= end; i++) {
                    sum += nums[i];
                }
                max = Math.max(max, sum);
            }
        }
        return max;
    }

    //优化之后 累加上次计算过的和
    private static int maxSubarray2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = Integer.MIN_VALUE;
        for (int begin = 0; begin < nums.length; begin++) {
            int sum = 0;
            for (int end = begin; end < nums.length; end++) {
                sum += nums[end];
                max = Math.max(max, sum);
            }
        }
        return max;
    }

    //求解begin-end最大连续子序列和
    static int maxSubarray3(int[] nums, int begin, int end) {
        if (end - begin < 2) {
            //当区间只有一个元素的时候，只剩下了一个元素了
            return nums[begin];
        }
        int mid = (begin + end) >> 1;
        int leftMax = Integer.MIN_VALUE;
        int leftSum = 0;
        for (int i = mid - 1; i >= begin; i--) {
            leftSum += nums[i];
            leftMax = Math.max(leftMax, leftSum);
        }
        int rightMax = Integer.MIN_VALUE;
        int rightSum = 0;
        for (int i = mid; i < end; i++) {
            rightSum += nums[i];
            rightMax = Math.max(rightMax, rightSum);
        }
        int max = leftMax + rightMax;
        return Math.max(max, Math.max(maxSubarray3(nums, begin, mid),
                maxSubarray3(nums, mid, end)));
    }
}